package or;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class T2488 {
    public int countSubarrays(int[] nums, int k) {
        int sum = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        int diff = 0;
        int kId = -1;
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            if (nums[i] > k) {
                diff++;
            } else if (nums[i] < k) {
                diff--;
            } else {
                kId = i;
                break;
            }
            if (map.containsKey(diff)){
                map.put(diff,map.get(diff)+1);
            }else {
                map.put(diff, 1);
            }
        }
        for (int i = kId; i < len; i++) {
            if (nums[i] > k) {
                diff++;
            } else if (nums[i] < k) {
                diff--;
            }
            if (map.containsKey(diff)) {
                sum += map.get(diff);
            }
            if (map.containsKey(diff - 1)) {
                sum += map.get(diff - 1);
            }
        }
        return sum;
    }

    @Test
    public void test() {

        int[] ints = {4,1,3,2};
        System.out.println(countSubarrays(ints, 1));
    }
}
